/*
 * iaqcore.c
 *
 * Created: 2019/8/9 14:32:49
 *  Author: YY
 */ 
#include "iaqcore.h"

//IAQ
struct io_descriptor *I2C_0_io;

uint8_t iaq_update = 1;

IAQ_VAL iaq_val = {
	.status=0xff,
	};

void iaq_read(void){
	static uint32_t iaq_read_tick = 0;
	
	uint8_t buf[16];
//	int i;
	IAQ_VAL iaq_temp_val;
	char* psts = NULL;
	
	if ( mx_hal_ms_ticker_read()-iaq_read_tick < 1000) 
		return;
		
	iaq_read_tick = mx_hal_ms_ticker_read();
	
	i2c_m_sync_set_slaveaddr(&I2C_0, 0x5A, I2C_M_SEVEN); //IAQ SLA

	if( 9!= io_read(I2C_0_io, buf, 9) ){
		//iaq_update = 1;
		iaq_val.status = 0x80;
		iaq_val.co2=0;
		iaq_val.res	=0;
		iaq_val.tvoc=0;
		//return;
	}else{
		iaq_temp_val.co2 = (buf[0]<<8)|buf[1];
		iaq_temp_val.status = buf[2];
		iaq_temp_val.res	= (buf[3]<<24)|(buf[4]<<16)|(buf[5]<<8)|buf[6];
		iaq_temp_val.tvoc = (buf[7]<<8)|buf[8];			
	}

	if( 0!=memcmp(&iaq_temp_val, &iaq_val, sizeof(IAQ_VAL)) ){
		iaq_update = 1;
		iaq_val = iaq_temp_val;
	}
	
	//buf0,1: co2 ppm
	//buf2 status: 0x00-> OK   0x10->RUNIN  0x01->BUSY 0x80 ERROR
	//buf3-6 res
	//buf7-8 tvoc
/*	
	for(i=0; i<9; i++){
		printf("%.2x ", buf[i]);
	}
	printf("\n");
*/	
	
	switch(iaq_val.status){
		case 0x00:
		psts = "OK";
		break;
		
		case 0x10:
		psts = "PreHeat";
		break;
		
		case 0x01:
		psts = "BUSY";
		break;
		
		case 0x80:
		psts = "ERROR";
		break;
		
		default:
		psts = "ERROR";
		break;
	}
	
	//printf("{'status':'%s','co2':%d,'tvoc':%d,'res':%ld}", psts, iaq_val.co2, iaq_val.tvoc, iaq_val.res);
	
}

void iaq_disp(void){
	char str[32];
	
	if( !iaq_update) return;
	
	iaq_update=0;

	switch(iaq_val.status){
		case 0x00:
		OLED_ShowString(0,6,"Status:OK     ");
		
		break;
		
		case 0x10:
		OLED_ShowString(0,6,"Status:PreHeat");
		break;
		
		case 0x01:
		OLED_ShowString(0,6,"Status:BUSY   ");
		break;
		
		//case 0x80:
		default:
		OLED_ShowString(0,6,"Status:ERROR  ");
		break;
	}
	
	//if( iaq_val.status==0x00)
	{//OK
		
		sprintf(str, "CO2 :%5d  ", iaq_val.co2);
		OLED_ShowString(0,2,str);
		
		sprintf(str, "TVOC:%5d  ", iaq_val.tvoc);
		OLED_ShowString(0,4,str);
		
		//sprintf(str,"RES :%8ld  ", iaq_val.res);
		//oled_puts(0,6,str);
	}
	
}

